package net.yienyien.process.bpel.util;

import java.util.Map;

import net.yienyien.process.bpel.BpelPackage;
import net.yienyien.process.bpel.DocumentRoot;

import org.eclipse.emf.common.util.EMap;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.xmi.XMLHelper;
import org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl;
import org.eclipse.wst.wsdl.Message;
import org.eclipse.wst.wsdl.WSDLPackage;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;

public class BpelSave extends XMLSaveImpl {

	public BpelSave(Map<?, ?> options, XMLHelper helper, String encoding) {
		super(options, helper, encoding);
	}

	public BpelSave(Map<?, ?> options, XMLHelper helper, String encoding,
			String xmlVersion) {
		super(options, helper, encoding, xmlVersion);

	}

	public BpelSave(XMLHelper helper) {
		super(helper);

	}

	@Override
	protected void saveEObjectSingle(EObject o, EStructuralFeature f) {
		if(BpelPackage.eINSTANCE.getVariable_MessageTypeRef().equals(f)) {
			saveMessageType(o, f);
		} else {
			super.saveEObjectSingle(o, f);
		}
	}
	
	
	public String getFreshNs(EMap<String, String> map) {
		String base="ns";
		int i=1;
		String current=base+i;
		while(map.get(current)!=null) {
			current=base+(++i);
		}
		return current;
	}
	
	protected void saveMessageType(EObject o, EStructuralFeature f) {
	   	Object value = helper.getValue(o, f);
	    
	    if (value != null && WSDLPackage.eINSTANCE.getMessage().isInstance(value)) {
	    	Message msg=(Message) value;
	    	StringBuffer buffer=new StringBuffer();
	    	
	    	
	    	String ns=msg.getQName().getNamespaceURI();
	    	String prefix=null;
	    	if(!helper.getPrefixToNamespaceMap().containsValue(ns)) {
	    		prefix=getFreshNs(helper.getPrefixToNamespaceMap());
	    		helper.getPrefixToNamespaceMap().put(prefix, ns);
	    		
	    	} else {
	    		for(Map.Entry<String,String> e: helper.getPrefixToNamespaceMap().entrySet()) {
	    			if(e.getValue().equals(ns)) {
	    				prefix=e.getKey();
	    				break;
	    			}
	    		}
	    	}
	    	
	    	buffer.append(prefix);
	    	buffer.append(":");
	    	buffer.append(msg.getQName().getLocalPart());
	        
	        if (!toDOM)
	        {
	          String name = helper.getQName(f);
	          doc.startAttribute(name);
	          doc.addAttributeContent(buffer.toString());
	          doc.endAttribute();
	        }
	        else
	        {
	          helper.populateNameInfo(nameInfo, f);
	          Attr attr = document.createAttributeNS(nameInfo.getNamespaceURI(), nameInfo.getQualifiedName());
	          attr.setNodeValue(buffer.toString());      
	          ((Element)currentNode).setAttributeNodeNS(attr);
	          handler.recordValues(attr, o, f, value);
	        }
	      }
	    }
	}